//系统级路由
import 'dart:convert';

import 'package:amoy_ticket/home/license_info_page.dart';
import 'package:amoy_ticket/model/common/abstract_json_object.dart';
import 'package:amoy_ticket/model/common/common_parent_widget.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';

import 'log_util.dart';
import 'router_item.dart';

final String MAIN = '/';
//打开URL
final String OPEN_URL = '/open-url/';
//证照信息页面
final String LICENSE_INFO = '/license-info/';

class RouterUtil {
  static FluroRouter router = FluroRouter();
  static GlobalKey<NavigatorState> navigatorKey = GlobalKey();
  static List<RouterItem> routerItemList = [
    RouterItem(LICENSE_INFO, LicenseInfoPage(), routerTitle: '证照信息'),
  ];

  /// 跳转到系统路由
  static void navigateTo(BuildContext context, String routerPath,
      {bool replace = false, bool clearStack = false}) async {
    LogUtil.get().d('跳转到路径$routerPath');
    await router.navigateTo(context, routerPath,
        transition: TransitionType.cupertino,
        replace: replace,
        clearStack: clearStack);
  }

  ///包含参数的Router
  static void navigateWithParameter(
      BuildContext context, String routerURL, String parm,
      {bool replace = false, bool clearStack = false}) async {
    var encodeURL = Uri.encodeComponent(parm);
    var routerURLAll = routerURL + encodeURL;

    LogUtil.get().d('跳转到路径$routerURLAll');
    await router.navigateTo(context, routerURLAll,
        replace: replace,
        transition: TransitionType.cupertino,
        clearStack: clearStack);
  }

  ////包含对象参数的Router
  static void navigateWithObject(
      BuildContext context, String routerURL, AbstractJsonObject parm,
      {bool replace = false, bool clearStack = false}) {
    var urlContion = json.encode(parm.toJson());
    navigateWithParameter(context, routerURL, urlContion,
        replace: replace, clearStack: clearStack);
  }

  ////包含对象参数的Router
  static void navigateWithMap(
      BuildContext context, String routerURL, Map<String, dynamic> parm,
      {bool replace = false, bool clearStack = false}) {
    var urlContion = json.encode(parm);
    navigateWithParameter(context, routerURL, urlContion,
        replace: replace, clearStack: clearStack);
  }

  ////包含参数的Router
  static void pop(BuildContext context) {
    Navigator.pop(context);
  }

  ///  配置路由信息
  static void intitRoutes() {
    ///初始化无参数的纯页面跳转链接
    routerItemList.forEach((RouterItem item) {
      LogUtil.get().i('开始添加无参数路由信息${item.routerTitle}');
      router.define(item.routerPath,
          handler: NoParmHandler(item.widget).getHandler());
    });
  }
}

//无参数通用Handler
class NoParmHandler {
  Widget widget;

  NoParmHandler(this.widget);

  Handler getHandler() {
    return Handler(
        handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
      return CommonParentWidget(widget);
    });
  }
}
